package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.BusinessConfigConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.AliOssUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private AliOssUtil aliOssUtil;
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1, 判断业务异常
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(queryWrapper);
        if (shoppingCartList == null || shoppingCartList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2,存orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        String address = addressBook.getProvinceName() + addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        orders.setAddress(address);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orderMapper.insert(orders);
        //3,存orders_detail表 (多条数据)
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderMapper.insertBatch(orderDetailList);
        //4,返回VO
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }

    @Override
    @CacheEvict(value = "shoppingCart",key = "#userId")
    public void paymentMock(OrdersPaymentDTO ordersPaymentDTO,Long userId) {
        //支付成功 改变状态
        Orders orders = orderMapper.selectById(ordersPaymentDTO.getOrderId());
        //业务逻辑判断
        //1,是否是本人支付,user_id
        if (!orders.getUserId().equals(userId)){
            throw new OrderBusinessException("非本人支付该订单");
        }
        //2,支付状态和订单状态是否是未支付
        if (!orders.getPayStatus().equals(Orders.UN_PAID) || !orders.getStatus().equals(Orders.PENDING_PAYMENT)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //3,修改订单状态,支付状态,支付时间
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.updateById(orders);
        //4,向商家发送来单提醒
        Map msg = new HashMap<>();
        msg.put("type",1); //1,来单提醒 2,客户催单
        msg.put("orderId",orders.getId());
        msg.put("content","来单了:"+orders.getNumber());
        webSocketServer.sendMessageToAllClient(JSON.toJSONString( msg));
        //5,清空购物车 (数据库+redis)
        shoppingCartMapper.delete(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId,userId));
    }

    @Override
    public PageResult historyOrders(int page, int pageSize, Integer status) {
        //分页查询历史订单
        Page<Orders> pageQuery = new Page<>(page,pageSize);
        //构造查询条件
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        queryWrapper.eq(status != null,Orders::getStatus,status);
        Page<Orders> pageResult = orderMapper.selectPage(pageQuery, queryWrapper);
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders orders : pageResult.getRecords()) {
            OrderVO orderVO = new OrderVO();
            List<OrderDetail> orderDetailList =orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,orders.getId()));
            //为每一个订单详情中的image生成访问路径
            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setImage(aliOssUtil.generatePresignedUrl(orderDetail.getImage()));
            }
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        PageResult pageResult1 = new PageResult();
        pageResult1.setTotal(pageResult.getTotal());
        pageResult1.setRecords(orderVOList);
        return pageResult1;
    }

    @Override
    public OrderVO orderDetail(Long id) {
        //根据订单id 查询订单详细信息
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,id));
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setImage(aliOssUtil.generatePresignedUrl(orderDetail.getImage()));
        }
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void userCancel(Long id) {
        //根据订单id取消订单
        // 待支付和待接单状态下，用户可直接取消订单,已支付待接单时需要给用户退款
        //- 取消订单后需要将订单状态修改为“已取消”
        //先查询订单
        Orders order = orderMapper.selectById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单状态
        if (order.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if(order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            //退款
            order.setPayStatus(Orders.REFUND);
        }
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    public void repetition(Long id) {
        //再来一单 将原订单中的商品重新加入到购物车中
        Orders order = orderMapper.selectById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,id));
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
            BeanUtils.copyProperties(orderDetail,shoppingCartDTO);
            shoppingCartService.add(shoppingCartDTO,BaseContext.getCurrentId());
        }
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页查询
        Page<Orders> page = new Page<>(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //构造查询条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(ordersPageQueryDTO.getNumber()),Orders::getNumber,ordersPageQueryDTO.getNumber());
        queryWrapper.eq(ordersPageQueryDTO.getStatus() != null,Orders::getStatus,ordersPageQueryDTO.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(ordersPageQueryDTO.getPhone()),Orders::getPhone,ordersPageQueryDTO.getPhone());
        //时间查询
        queryWrapper.between(ordersPageQueryDTO.getBeginTime() != null && ordersPageQueryDTO.getEndTime() != null,Orders::getOrderTime,ordersPageQueryDTO.getBeginTime(),ordersPageQueryDTO.getEndTime());
        Page<Orders> pageResult = orderMapper.selectPage(page, queryWrapper);
        //orderDishes 订单包含的菜品 以字符串形式展示 将Orders转成OrderVO
        List<OrderVO> orderVOList = getOrderVOList(pageResult);
        return new PageResult(pageResult.getTotal(),orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        //获取各个状态的订单数量 待接单数量,待配送数量,配送中数量
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer toBeConfirmed = Math.toIntExact(orderMapper.selectCount(new LambdaQueryWrapper<Orders>().eq(Orders::getStatus, Orders.TO_BE_CONFIRMED)));
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        Integer confirmed = Math.toIntExact(orderMapper.selectCount(new LambdaQueryWrapper<Orders>().eq(Orders::getStatus, Orders.CONFIRMED)));
        orderStatisticsVO.setConfirmed(confirmed);
        Integer deliveryInProgress = Math.toIntExact(orderMapper.selectCount(new LambdaQueryWrapper<Orders>().eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)));
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //商家接单 将订单状态改为待派送
        Orders orders = orderMapper.selectById(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //商家拒单 将订单状态修改为已取消 支付状态改为退款
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //获取支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus.equals(Orders.PAID)){
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        //商家取消订单 用户联系商家取消订单
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        //- 商家已接单状态和派送中状态下，用户取消订单需电话沟通商家
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus().equals(Orders.CONFIRMED) || orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            //已接单和派送中状态 取消订单
            //支付状态 退款
            if (orders.getPayStatus().equals(Orders.PAID)){
                orders.setPayStatus(Orders.REFUND);
            }
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.updateById(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    @Override
    public void delivery(Long id) {
        //商品派送 订单状态改为派送中
        Orders orders = orderMapper.selectById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateById(orders);
    }

    @Override
    public void complete(Long id) {
        //订单完成 订单状态改为已完成 送达时间改为当前时间
        Orders orders = orderMapper.selectById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    public void processExceptionOrder(LocalDateTime time, Integer status) {
        //time > 订单创建时间 且 订单状态为 status
        //构建查询条件
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(Orders::getOrderTime,time);
        queryWrapper.eq(Orders::getStatus,status);
        List<Orders> ordersList = orderMapper.selectList(queryWrapper);
       if (ordersList == null || ordersList.isEmpty()){
           return;
       }
       if (Objects.equals(status, Orders.PENDING_PAYMENT)){
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("订单支付超时");
               orders.setCancelTime(LocalDateTime.now());
               orderMapper.updateById(orders);
           }
       }
       if (Objects.equals(status, Orders.DELIVERY_IN_PROGRESS)){
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.COMPLETED);
               orders.setDeliveryTime(LocalDateTime.now());
               orderMapper.updateById(orders);
           }
       }
    }

    @Override
    public void reminder(Long id) {
        //客户催单
        Orders orders = orderMapper.selectById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","用户催单:"+orders.getNumber());
        webSocketServer.sendMessageToAllClient(JSON.toJSONString(map));
    }

    private List<OrderVO> getOrderVOList(Page<Orders> pageResult){
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = pageResult.getRecords();
        for (Orders orders : ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDishes(getOrderDishes(orders));
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }

    private String getOrderDishes(Orders orders) {
        //通过订单id获取订单菜品信息 并将菜品信息拼接成字符串 例如:宫爆鸡丁*3
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,orders.getId()));
        StringBuilder orderDishes = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDishes.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(",");
        }
        return orderDishes.toString();
    }
}

